import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import { useHistory, useParams } from 'react-router'
import { useEffect } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import {
  getArticleDetail,
  geyCommentList,
  getMoreCommentList,
  followUser,
} from '@/store/actions/article'
import { RootState } from '@/store'
import classNames from 'classnames'
import dayjs from 'dayjs'
import NoComment from './components/NoneComment/index'
import CommentItem from './components/Commentltem/index'
import CommentFooter from './components/CommentFooter/index'
import Share from './components/share/index'
import { InfiniteScroll } from 'antd-mobile-v5'
// 文章高亮
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import { useRef, useState } from 'react'
import { Drawer } from 'antd-mobile'

const Article = () => {
  const history = useHistory()
  const [isShowAuthor, setShowAuthor] = useState(false)
  const authorRef = useRef<HTMLDivElement>(null)
  const { id } = useParams<{ id: string }>()
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getArticleDetail(id))
  }, [dispatch, id])

  const { detail, comment } = useSelector((state: RootState) => state.article)
  useEffect(() => {
    // 进行代码高亮
    const codes = document.querySelectorAll('.dg_html pre > code')
    codes.forEach((item) => {
      hljs.highlightElement(item as HTMLElement)
    })
  }, [detail])
  // 进行页面滚动后在导航栏显示文章作者
  useEffect(() => {
    const onscroll = function () {
      const rect = authorRef.current?.getBoundingClientRect()
      if (rect && rect.top <= 0) {
        setShowAuthor(true)
      } else {
        setShowAuthor(false)
      }
    }
    document.addEventListener('scroll', onscroll)
    return () => {
      document.removeEventListener('scroll', onscroll)
    }
  })
  useEffect(() => {
    dispatch(geyCommentList(id))
  }, [dispatch, id])
  // 分享
  const [share, setShare] = useState(false)
  const onCloseShare = () => {
    setShare(false)
  }
  // 加载更多
  const hasMore = comment.last_id !== comment.end_id
  const loadMore = async () => {
    await dispatch(getMoreCommentList(id, comment.last_id))
  }
  // 点击关注
  const onFollow = () => {
    dispatch(followUser(detail.aut_id, detail.is_followed))
  }
  // 点击评论滑动到评论列表
  const commentRef = useRef<HTMLDivElement>(null)
  const isShowComment = useRef(false)
  const goComment = () => {
    if (isShowComment.current) {
      window.scrollTo(0, 0)
    } else {
      window.scrollTo(0, commentRef.current!.offsetTop)
    }
    isShowComment.current = !isShowComment.current
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar
          className="NavBar"
          onLeftClick={() => history.go(-1)}
          extra={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {isShowAuthor ? (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  detail.is_followed ? 'followed' : ''
                )}
                onClick={onFollow}
              >
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          ) : (
            ''
          )}
        </NavBar>

        <>
          <div className="wrapper">
            <div className="article-wrapper">
              {/* 文章描述信息栏 */}
              <div className="header">
                <h1 className="title">{detail.title}</h1>

                <div className="info">
                  <span>{detail.pubdate}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authorRef}>
                  <img src={detail.aut_photo} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span
                    onClick={onFollow}
                    className={classNames('follow', {
                      followed: detail.is_followed,
                    })}
                  >
                    {detail.is_followed ? '已关注' : '关注'}
                  </span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: detail.content,
                  }}
                ></div>
                <div className="date">
                  发布文章时间：{dayjs(detail.pubdate).format('YYYY-MM-DD')}
                </div>
              </div>
            </div>
            <div className="comment">
              {/* 评论总览信息 */}
              {/* <Sticky top={46}> */}
              <div className="comment-header" ref={commentRef}>
                <span>全部评论（{detail.comm_count}）</span>
                <span>{detail.like_count} 点赞</span>
              </div>
            </div>
            {detail.comm_count === 0 ? (
              <NoComment></NoComment>
            ) : (
              comment.results?.map((item) => (
                <CommentItem key={item.com_id} comment={item}></CommentItem>
              ))
            )}
          </div>
          <InfiniteScroll
            hasMore={hasMore}
            loadMore={loadMore}
          ></InfiniteScroll>
        </>
      </div>
      <CommentFooter
        goComment={goComment}
        onShare={() => setShare(true)}
      ></CommentFooter>
      {/* 分享抽屉 */}
      <Drawer
        className="drawer-share"
        position="bottom"
        children={''}
        sidebar={<Share onClose={onCloseShare} />}
        open={share}
        onOpenChange={onCloseShare}
      />
    </div>
  )
}

export default Article
